﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FyndSharp.BusinessLogic;
using System.Web.Security;
using System.Web.Configuration;
using System.Configuration;

namespace Fynd.Hermes.Web.Objects
{
    public class ContextModule : IHttpModule
    {
        public static string GetSessionCookieName()
        {
            SessionStateSection sessionStateSection = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
            return sessionStateSection.CookieName;
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
            context.PostAcquireRequestState += new EventHandler(OnPostAcquireRequestState);
        }
        public void Dispose()
        {

        }
        private void OnPostAcquireRequestState(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext ctx = app.Context;
            if (ctx.Session == null)
            {
                return;
            }
            object theUserId = ctx.Session[Global.HttpSessionKeyUserId];
            if (null == theUserId)
            {
                FormsAuthentication.SignOut();
                return;
            }
            try
            {
                DefaultLogicFactory factory = new DefaultLogicFactory();
                UserLogic userLogic = factory.CreateLogic<UserLogic>(new AnonymousUser());
                UserInfomation theUser = userLogic.FetchUserBy(theUserId.ToString());
                if (null != theUser)
                {
                    ctx.Items.Add(Global.HttpContextKeyUser, theUser);
                }
                else
                {
                    FormsAuthentication.SignOut();
                    ctx.Response.Redirect(FormsAuthentication.LoginUrl, true);
                }
            }
            catch
            {
                FormsAuthentication.SignOut();
            }
        }
        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext ctx = app.Context;
            try
            {
                string sessionKey = GetSessionCookieName();
                if(!String.IsNullOrEmpty(ctx.Request.Form[sessionKey]))
                {
                    UpdateCookie(sessionKey, ctx.Request.Form[sessionKey], ctx);
                }
                else if (!String.IsNullOrEmpty(ctx.Request.QueryString[sessionKey]))
                {
                    UpdateCookie(sessionKey, ctx.Request.QueryString[sessionKey], ctx);
                }

                string authKey = FormsAuthentication.FormsCookieName;
                if (!String.IsNullOrEmpty(ctx.Request.Form[authKey]))
                {
                    UpdateCookie(authKey, ctx.Request.Form[authKey], ctx);
                }
                else if (!String.IsNullOrEmpty(ctx.Request.QueryString[authKey]))
                {
                    UpdateCookie(authKey, ctx.Request.QueryString[authKey], ctx);
                }
            }
            catch
            {

            }
        }
        private void UpdateCookie(string name, string value, HttpContext ctx)
        {
            HttpCookie cookie = ctx.Request.Cookies[name];
            if (null == cookie)
            {
                cookie = new HttpCookie(name);
            }
            cookie.Value = value;
            ctx.Request.Cookies.Set(cookie);
        }
    }
}